const axios = require('axios')
const { decode } = require('./charset')

const instance = axios.create({
  timeout: 2000
})

// instance.interceptors.response.use(function (response) {
//   // Do something with response data
//   return response.data
// }, function (error) {
//   // Do something with response error
//   return Promise.reject(error)
// })

function request (config, source = null, isGbk = false) {
  const options = {}
  if (source && source.httpUserAgent) {
    options.headers = {
      'User-Agent': source.httpUserAgent
    }
  }
  // 强制arraybuffer 后面检测编码
  options.responseType = 'arraybuffer'
  return instance.request({
    ...config,
    ...options
  }).then(res => {
    if (isGbk) {
      return decode(res.data, 'gbk')
    }
    const data = res.data.toString()
    // 应该足够了
    const regex = /charset="?gbk"?/i
    if (regex.test(data)) {
      return decode(res.data, 'gbk')
    }
    return data
  })
}

module.exports = {
  get (url, params = {}, source = null, isGbk = false) {
    return request({
      method: 'get',
      url,
      params
    }, source, isGbk)
  },
  post (url, data, source = null, isGbk = false) {
    return request({
      method: 'post',
      url,
      data
    }, source, isGbk)
  }

}
